﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using WebApi.Models;

namespace WebApi.Services
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class AdController : ControllerBase
    {
        private readonly AdService _adService;

        public AdController(AdService adService)
        {
            _adService = adService;
        }

        [HttpGet]
        public ActionResult<List<Ad>> Get()
        {
            return _adService.Get();
        }

        [HttpGet("{id:length(24)}", Name = "GetAd")]
        public ActionResult<Ad> Get(string id)
        {
            var ad = _adService.Get(id);

            if (ad == null)
            {
                return NotFound();
            }

            return ad;
        }

        [HttpPost]
        public ActionResult<Ad> Create(Ad ad)
        {
            _adService.Create(ad);

            return CreatedAtRoute("GetAd", new { id = ad.Id.ToString() }, ad);
        }

        [HttpPut("{id:length(24)}")]
        public IActionResult Update(string id, Ad adIn)
        {
            var ad = _adService.Get(id);

            if (ad == null)
            {
                return NotFound();
            }

            _adService.Update(id, adIn);

            return NoContent();
        }

        [HttpDelete("{id:length(24)}")]
        public IActionResult Delete(string id)
        {
            var ad = _adService.Get(id);

            if (ad == null)
            {
                return NotFound();
            }

            _adService.Remove(ad.Id);

            return NoContent();
        }
    }
}
